package com.bestcem.xm.qdes.handler.impor.type;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.qdes.handler.impor.KeyWordHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Component
public class KeywordMatrixrowHandler implements KeyWordHandler {
    private static final Pattern ATTR_PATTERN = Pattern.compile("\\[(.*?)\\]");

    @Override
    public Integer handler(String qType, JSONArray rawItems, JSONObject questionDict) {
        // 矩阵行解析
        if (rawItems == null || rawItems.isEmpty()) {
            return 0;
        }
        JSONArray rowMatrixCommon = Optional.ofNullable(rawItems.getJSONArray(0)).orElse(new JSONArray());
        String matrixAttrStr = rowMatrixCommon.size() > 2 ? rowMatrixCommon.getString(2).trim() : "";
        questionDict.putAll(parseMatrixrowGroupCommonAttr(matrixAttrStr));

        JSONArray rawMatrixrows = new JSONArray();
        if (rowMatrixCommon.size() > 1) {
            for (int i = 1; i < rawItems.size(); i++) {
                rawMatrixrows.add(rawItems.get(i));
            }
        }
        JSONArray retItems = new JSONArray();
        questionDict.put("rows_items", retItems);

        String dispSelect = Optional.ofNullable(questionDict.getString("dispSelect")).orElse("");
        boolean codeSelect = Optional.ofNullable(questionDict.getBoolean("codeSelect")).orElse(false);

        boolean hasJumpCode = false;
        int totalGidCountTmp = rawMatrixrows.size();
        for (int i = 0; i < rawMatrixrows.size(); i++) {
            JSONArray rawMatrix = rawMatrixrows.getJSONArray(i);
            Object matrixCid = rawMatrix.get(0);
            Object matrixTitle = rawMatrix.get(1);
            String matrixAttr = rawMatrix.size() > 2 ? rawMatrix.getString(2) : "";
            String dispPlasterCode = rawMatrix.size() > 3 ? rawMatrix.getString(3) : ""; // 显示代码/抹灰代码
            String jumpCode = rawMatrix.size() > 4 ? rawMatrix.getString(4) : ""; // 跳转代码
            String autoCode = rawMatrix.size() > 5 ? rawMatrix.getString(5) : ""; // 自动勾选代码

            JSONObject matrixrowDict = new JSONObject();
            matrixrowDict.put("oid", matrixCid);
            matrixrowDict.put("title", matrixTitle);
            matrixrowDict.put("type", "R");
            matrixrowDict.put("rightWord", "");

            matrixrowDict.putAll(parseMatrixAttr(matrixAttr));
            
            if ("1".equals(dispSelect) && codeSelect) {
                // 显示代码
                matrixrowDict.put("disp_code", dispPlasterCode);
            } else if ("1".equals(dispSelect) && !codeSelect) {
                // 抹灰代码
                matrixrowDict.put("plaster_code", dispPlasterCode);
            }

            if (StringUtils.isNotEmpty(jumpCode)) {
                hasJumpCode = true;
                matrixrowDict.put("jump_code", jumpCode);
            }
            if (StringUtils.isNotEmpty(autoCode)) {
                matrixrowDict.put("auto_code", autoCode);
            }
            retItems.add(matrixrowDict);
        }
        if (hasJumpCode) {
            questionDict.put("jumpSelect", 1);
        }
        return totalGidCountTmp;
    }

    @Override
    public String getType() {
        return "矩阵行;分类";
    }

    private JSONObject parseMatrixrowGroupCommonAttr(String attrstr) {
        // 矩阵行标识 属性处理
        JSONObject retDict = new JSONObject();
        if (StringUtils.isEmpty(attrstr)) {
            return retDict;
        }

        // [顺序#随机][右极文字][答案唯一] --> ['顺序#随机', '右极文字', '答案唯一']
        Matcher attrMatcher = ATTR_PATTERN.matcher(attrstr);
        List<String> attributes = new ArrayList<>();
        while (attrMatcher.find()) {
            attributes.add(attrMatcher.group(1));
        }

        for (String attr : attributes) {
            attr = attr.trim();
            if (attr.startsWith("顺序#")) {
                String[] vals = attr.split("#");
                if (vals.length > 1) {
                    String val = attr.split("#")[1];
                    retDict.put("rows_random", "随机".equals(val) ? true : "循环".equals(val) ? "sort" : "倒序"
                        .equals(val) ? "reverse" : false);
                }
            } else if ("答案唯一".equals(attr)) {
                retDict.put("unique", true);
            } else if ("右极文字".equals(attr)) {
                retDict.put("showMatrixRWord", true);
            }
        }
        return retDict;
    }

    private JSONObject parseMatrixAttr(String attrstr) {
        // 矩阵行的属性设置
        JSONObject retDict = new JSONObject();
        retDict.put("required", true); // 矩阵题增加 默认矩阵行必答
        if (StringUtils.isEmpty(attrstr)) {
            return retDict;
        }
        // [非必答][右极文字#右极1][开放#必填#唯一#小数#1-10-2] --> ['非必答', '右极文字#右极1', '开放#必填#唯一#小数#1-10-2']
        Matcher attrMatcher = ATTR_PATTERN.matcher(attrstr);
        List<String> attributes = new ArrayList<>();
        while (attrMatcher.find()) {
            attributes.add(attrMatcher.group(1));
        }

        for (String attr : attributes) {
            attr = attr.trim();
            if ("非必答".equals(attr)) {
                retDict.put("required", false);
            } else if ("必答".equals(attr)) {
                retDict.put("required", true);
            } else if (attr.startsWith("右极文字#")) {
                retDict.put("rightWord", attr.split("#")[1]);
            } else if ("固定".equals(attr)) {
                retDict.put("fixed", true);
            } else if (attr.startsWith("开放")) {
                List<String> vals = Arrays.stream(attr.split("#")).collect(Collectors.toList());
                retDict.put("is_open", true);
                retDict.putAll(parseOptionOpen(vals.subList(1, vals.size())));
            }
        }
        return retDict;
    }
}
